package com.cloud.picture.manager.upload;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.cloud.picture.exception.BusinessException;
import com.cloud.picture.model.enums.ErrorCodeEnum;
import com.cloud.picture.utils.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import static com.cloud.picture.constant.FileConstants.ALLOW_CONTENT_TYPE;
import static com.cloud.picture.constant.FileConstants.FILE_UPLOAD_SIZE_LIMIT;

/**
 * @author syf
 */
@Service
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        // 下载文件到临时目录
        HttpUtil.downloadFile(fileUrl, file);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        // 从 URL 中提取文件名
        return fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    }

    @Override
    protected String validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(fileUrl == null, ErrorCodeEnum.PARAMS_ERROR, "上传文件不能为空");
        try {
            // 1. 校验 URL 格式
            new URL(fileUrl);
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "URL地址格式错误");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCodeEnum.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求验证文件是否存在
        String contentType;
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            // 未正常返回
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return fileUrl;
            }
            // 4. 校验文件类型
            contentType = response.header("Content-Type");
            if (CharSequenceUtil.isNotBlank(contentType)) {
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPE.contains(contentType.toLowerCase()),
                        ErrorCodeEnum.PARAMS_ERROR, "文件类型错误");
            }
            // 5. 校验文件大小
            String contentSize = response.header("Content-Length");
            if (CharSequenceUtil.isNotBlank(contentSize)) {
                try {
                    long fileSize = Long.parseLong(contentSize);
                    ThrowUtils.throwIf(fileSize > FILE_UPLOAD_SIZE_LIMIT,
                            ErrorCodeEnum.PARAMS_ERROR, "文件大小不能超过" + FILE_UPLOAD_SIZE_LIMIT / 1024 / 1024 + "MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        }
        return contentType;
    }
}
